package com.atguigu.tingshu.order.listener;

import com.atguigu.tingshu.order.service.OrderPayService;
import com.rabbitmq.client.Channel;
import lombok.SneakyThrows;
import lombok.extern.log4j.Log4j2;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/***
 * 监听订单的支付消息
 */
@Component
@Log4j2
public class OrderPaymentListener {

    @Autowired
    private OrderPayService orderPayService;

    /**
     * 监听订单的支付消息,修改订单的状态
     * @param channel
     * @param message
     */
    @SneakyThrows
    @RabbitListener(queues = "payment_tingshu_order_queue")
    public void orderPaymentListener(Channel channel, Message message){
        //获取消息的内容
        String orderNo = new String(message.getBody());
        //获取消息的属性
        MessageProperties messageProperties = message.getMessageProperties();
        //获取消息的编号
        long deliveryTag = messageProperties.getDeliveryTag();
        try {
            //修改订单的支付状态
            orderPayService.updateOrderPaid(orderNo);
            //确认消息
            channel.basicAck(deliveryTag, false);
        }catch (Exception e){
            if(messageProperties.getRedelivered()){
                //两次都失败
                channel.basicReject(deliveryTag, false);
            }else{
                //再取消一次
                channel.basicReject(deliveryTag, true);
            }
        }
    }
}
